package com.xjk.shiro.controller;

import com.xjk.shiro.entity.User;
import com.xjk.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author: XJK
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String home(){
        return "index";
    }

    @RequestMapping("/regist")
    public String register(){
        return "regist";
    }

    @RequestMapping("/userRegist")
    public String register(User user) {
        try {
            userService.registeredUser(user);
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            return "regist";
        }
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
    @RequestMapping(value = "/userLogin",method = RequestMethod.POST)
    public String login(String username, String password) {
        //获取主题对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            System.out.println("登录成功！！！");
        } catch (UnknownAccountException e) {
            System.out.println("用户错误！！！");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误！！！");
        }

        // 只有登录成功了才能授权
        if(subject.isAuthenticated()){
            // 当前用户是否是admin角色用户
            if(subject.hasRole("admin")){
                // 当前这个 admin 是否有"admin:manage:admin"权限
                if (subject.isPermitted("admin:manage:admin")){
                    return "manager";
                }
            }
            return "product";
        }

        return "login";
    }
}
